#include "http_server_impl.h"
#include "utils_log.h"
#include <mongoose.h>
#include <curl/curl.h>
#include <cstring>
#include <memory>
#include <chrono>
#include <thread>
#include <unistd.h>
#include <sys/stat.h>
#include <filesystem>
#include "utils_file_ex.h"
#include <regex>
#include <sstream>
#include <arpa/inet.h>
#include "common_property.h"

namespace El {
namespace WebServer {

IHttpServer &IHttpServer::GetInstance()
{
    return HttpServerImpl::GetInstance();
}

HttpServerImpl &HttpServerImpl::GetInstance()
{
    static HttpServerImpl instance;
    return instance;
}

HttpServerImpl::HttpServerImpl() {
    InitializeCurl();
}

HttpServerImpl::~HttpServerImpl()
{
    Stop();
    CleanupCurl();
}

bool HttpServerImpl::Start()
{
    if (running_) {
        return false;
    }

    mgr_ = new mg_mgr;
    mg_mgr_init(mgr_);

    const char *address = "https://0.0.0.0:80";
    mg_connection *conn = mg_http_listen(mgr_, address, HandleHttpEvent, this);
    if (conn == nullptr) {
        EL_ERROR("Failed to start HTTPS server on {}", address);
        mg_mgr_free(mgr_);
        delete mgr_;
        mgr_ = nullptr;
        return false;
    }

    running_ = true;
    serverThread_ = std::thread([this]() {
        while (running_) {
            mg_mgr_poll(mgr_, 10);
        }
    });

    EL_INFO("HTTPS server started on {} with TLS enabled", address);
    return true;
}

void HttpServerImpl::Stop()
{
    if (!running_) {
        return;
    }

    running_ = false;
    if (serverThread_.joinable()) {
        serverThread_.join();
    }

    if (mgr_) {
        mg_mgr_free(mgr_);
        delete mgr_;
        mgr_ = nullptr;
    }

    EL_INFO("HTTPS server stopped");
}

bool HttpServerImpl::RegisterWebSocketHandler(const std::string &uri_pattern, WebSocketEventHandler handler)
{
    // 创建WebSocket路由项
    WebSocketRouteItem route;
    route.uri_pattern = uri_pattern;
    route.handler = handler;

    try {
        route.uri_regex = std::regex(uri_pattern);
    } catch (const std::regex_error &e) {
        EL_ERROR("Invalid WebSocket URI pattern: {}, error: {}", uri_pattern, e.what());
        return false;
    }

    // 添加到WebSocket路由表
    ws_routes_.push_back(route);

    EL_INFO("WebSocket handler registered for pattern: {}", uri_pattern);
    return true;
}

bool HttpServerImpl::SendWebSocketTextMessage(void *connection, const std::string &message)
{
    auto *c = static_cast<mg_connection *>(connection);
    if (c != nullptr && c->is_websocket) {
        mg_ws_send(c, message.c_str(), message.size(), WEBSOCKET_OP_TEXT);
        return true;
    }
    return false;
}

bool HttpServerImpl::SetMountPoint(const std::string &dir)
{
    root_dir_ = dir;
    EL_INFO("Web root directory set to: {}", dir);
    return true;
}

bool HttpServerImpl::RegisterHandler(const std::string &method, const std::string &uri_pattern, HttpHandler handler)
{
    try {
        RouteItem route{method, uri_pattern, handler, std::regex(uri_pattern)};
        routes_.push_back(route);
        EL_INFO("Handler registered for method: {}, URI pattern: {}", method, uri_pattern);
        return true;
    } catch (const std::regex_error &e) {
        EL_ERROR("Invalid regex pattern: {}, error: {}", uri_pattern, e.what());
        return false;
    }
}

bool HttpServerImpl::MatchRoute(const std::string &method, const std::string &uri, RouteItem *route)
{
    // 首先检查普通HTTP路由
    for (const auto &r : routes_) {
        if (r.method == method && std::regex_match(uri, r.uri_regex)) {
            if (route != nullptr) {
                *route = r;
            }
            return true;
        }
    }

    return false;
}

bool HttpServerImpl::FindWebSocketRoute(const std::string &uri, WebSocketRouteItem *route)
{
    for (const auto &r : ws_routes_) {
        if (std::regex_match(uri, r.uri_regex)) {
            if (route != nullptr) {
                *route = r;
            }
            return true;
        }
    }

    return false;
}

bool HttpServerImpl::ValidateToken(const std::string &token)
{
    if (Common::CommonProperty::GetInstance().GetProperty("protocol.auth", "on") == "off") {
        EL_INFO("Auth is off");
        return true;
    }

    // 检查token是否在已授权集合中
    return bearer_tokens_.find(token) != bearer_tokens_.end();
}

bool HttpServerImpl::IsAuthExempt(const std::string &uri)
{
    // 检查是否匹配任一免鉴权正则表达式
    for (const auto &pattern : auth_exempt_urls_) {
        if (std::regex_match(uri, pattern)) {
            return true;
        }
    }
    return false;
}

bool HttpServerImpl::ValidateAuthHeader(const mg_str *auth_header)
{
    if (Common::CommonProperty::GetInstance().GetProperty("protocol.auth", "on") == "off") {
        EL_INFO("Auth is off");
        return true;
    }

    if (auth_header == nullptr) {
        return false;
    }

    std::string auth_str(auth_header->ptr, auth_header->len);
    if (auth_str.substr(0, 7) != "Bearer ") {
        return false;
    }

    std::string token = auth_str.substr(7);
    return ValidateToken(token);
}

void HttpServerImpl::HandleHttpRequest(mg_connection *c, int ev, void *ev_data)
{
    (void)ev;
    struct mg_http_message *hm = (struct mg_http_message *)ev_data;

    // 提取请求方法和URI
    std::string method(hm->method.ptr, hm->method.len);
    std::string uri(hm->uri.ptr, hm->uri.len);

    // 提取不带查询参数的路径部分，用于路由匹配
    std::string path = uri;
    size_t queryPos = uri.find('?');
    if (queryPos != std::string::npos) {
        path = uri.substr(0, queryPos);
    }

    EL_DEBUG("Received HTTP request: {} {}, path: {}", method, uri, path);

    // 检查是否有鉴权豁免
    bool isExempt = IsAuthExempt(path);

    // 尝试匹配WebSocket路由
    WebSocketRouteItem wsRoute;
    bool isWebSocketRequest = mg_http_get_header(hm, "Upgrade") != nullptr && // 检查是否包含WebSocket升级头
                              FindWebSocketRoute(path, &wsRoute);
    if (isWebSocketRequest) {

        if (!isExempt) {
            // 首先尝试从URL query参数中获取token
            bool is_authorized = false;
            char token_buf[256] = {0};
            if (mg_http_get_var(&hm->query, "token", token_buf, sizeof(token_buf)) > 0) {
                std::string token(token_buf);
                is_authorized = ValidateToken(token);
            }

            if (!is_authorized) {
                EL_WARN("WebSocket connection rejected: unauthorized uri: {}", uri.c_str());
                mg_http_reply(c, 401, nullptr, "Unauthorized");
                return;
            }
        }

        // 保存连接与URI的映射关系
        {
            std::lock_guard<std::mutex> lock(ws_mutex_);
            auto &state = ws_connections_[static_cast<int64_t>(c->id)];
            state.conn = c;
            state.uri = path;
        }

        // WebSocket连接不需要鉴权，直接升级
        EL_INFO("WebSocket connection upgraded: {} {}", method, path);
        mg_ws_upgrade(c, hm, NULL);
        return;
    } else {
        // 首先尝试代理处理
        HttpRequest request;
        request.method = method;
        request.uri = path;
        request.body = std::string(hm->body.ptr, hm->body.len);

        // 获取请求头
        for (size_t i = 0; i < MG_MAX_HTTP_HEADERS && hm->headers[i].name.len > 0; i++) {
            auto &h = hm->headers[i];
            request.headers[std::string(h.name.ptr, h.name.len)] = std::string(h.value.ptr, h.value.len);
        }

        HttpResponse proxy_response;
        if (HandleProxyRequest(request, proxy_response)) {
            // 发送代理响应
            std::string headers_str = "Content-Type: " + proxy_response.content_type + "\r\n";
            mg_http_reply(c, proxy_response.status_code, headers_str.c_str(), "%s", proxy_response.body.c_str());
            return;
        }

        // 尝试匹配普通HTTP路由
        RouteItem route;
        if (MatchRoute(method, path, &route)) {
            // 检查是否需要鉴权
            if (!isExempt) {
                struct mg_str *auth_header = mg_http_get_header(hm, "Authorization");
                if (!ValidateAuthHeader(auth_header)) {
                    EL_WARN("HTTP request rejected: unauthorized, uri: {}", path);
                    mg_http_reply(c, 401, nullptr, "Unauthorized");
                    return;
                }
            }

            // 调用处理函数获取响应
            HttpResponse response = route.handler(request);

            // 使用mg_http_reply发送响应
            mg_http_reply(c, response.status_code, ("Content-Type: " + response.content_type + "\r\n").c_str(), "%s",
                          response.body.c_str());
        } else {
            // 没有匹配的路由，提供静态文件服务
            struct mg_http_serve_opts opts = {.root_dir = root_dir_.c_str(),
                                              .ssi_pattern = nullptr,
                                              .extra_headers = "Cache-Control: no-cache\r\n",
                                              .mime_types = nullptr,
                                              .page404 = nullptr,
                                              .fs = nullptr};
            mg_http_serve_dir(c, hm, &opts);
        }
    }
}

void HttpServerImpl::HandleHttpEvent(mg_connection *c, int ev, void *ev_data, void *fn_data)
{
    auto *server = static_cast<HttpServerImpl *>(fn_data);
    if (server == nullptr) {
        return;
    }

    switch (ev) {
        case MG_EV_HTTP_MSG: {
            EL_DEBUG("HTTP message received");
            server->HandleHttpRequest(c, ev, ev_data);
            break;
        }
        case MG_EV_WS_OPEN: {
            std::string uri;
            {
                std::lock_guard<std::mutex> lock(server->ws_mutex_);
                auto &state = server->ws_connections_[static_cast<int64_t>(c->id)];
                state.conn = c;
                state.uri = server->ws_connections_[static_cast<int64_t>(c->id)].uri; // URI在HandleHttpRequest中已设置
                state.info.uri = state.uri;
                char ip_str[INET6_ADDRSTRLEN];
                state.info.remote_ip =
                    inet_ntop(c->rem.is_ip6 ? AF_INET6 : AF_INET, c->rem.ip, ip_str, INET6_ADDRSTRLEN)
                        ? std::string(ip_str)
                        : "unknown";
                state.info.remote_port = mg_ntohs(c->rem.port);
                state.info.is_secure = c->is_tls;
                state.info.connect_time = std::chrono::system_clock::now();
                uri = state.uri;

                EL_DEBUG("WebSocket opened for URI: {}, connection_id: {} remote_ip: {} remote_port: {}", uri, c->id,
                          state.info.remote_ip.c_str(), state.info.remote_port);
            }

            // 查找匹配的WebSocket处理器
            WebSocketRouteItem route;
            if (server->FindWebSocketRoute(uri, &route)) {
                auto event = std::make_shared<WebSocketEvent>();
                event->type = WebSocketEventType::Connect;
                event->connection = c;
                event->connection_id = static_cast<int64_t>(c->id);
                route.handler(event);
            } else {
                EL_WARN("No WebSocket handler found for URI: {}", uri);
            }
            break;
        }
        case MG_EV_WS_MSG: {
            auto *wm = static_cast<mg_ws_message *>(ev_data);
            std::string uri;
            {
                std::lock_guard<std::mutex> lock(server->ws_mutex_);
                auto it = server->ws_connections_.find(static_cast<int64_t>(c->id));
                if (it != server->ws_connections_.end()) {
                    uri = it->second.uri;
                }
            }

            if (!uri.empty()) {
                // 查找匹配的WebSocket处理器
                WebSocketRouteItem route;
                if (server->FindWebSocketRoute(uri, &route)) {
                    auto event = std::make_shared<WebSocketEvent>();
                    event->type = WebSocketEventType::Message;
                    event->connection = c;
                    event->connection_id = static_cast<int64_t>(c->id);
                    event->message = std::string(wm->data.ptr, wm->data.len);
                    route.handler(event);
                } else {
                    EL_WARN("No WebSocket handler found for URI: {}", uri);
                }
            } else {
                EL_ERROR("WebSocket message received but URI not found in connection map");
            }
            break;
        }
        case MG_EV_CLOSE: {
            EL_DEBUG("Connection closed");
            if (c->is_websocket) {
                std::string uri;
                {
                    std::lock_guard<std::mutex> lock(server->ws_mutex_);
                    auto it = server->ws_connections_.find(static_cast<int64_t>(c->id));
                    if (it != server->ws_connections_.end()) {
                        uri = it->second.uri;
                        server->ws_connections_.erase(it);
                    }
                }

                if (!uri.empty()) {
                    // 查找匹配的WebSocket处理器
                    WebSocketRouteItem route;
                    if (server->FindWebSocketRoute(uri, &route)) {
                        auto event = std::make_shared<WebSocketEvent>();
                        event->type = WebSocketEventType::Disconnect;
                        event->connection = c;
                        event->connection_id = static_cast<int64_t>(c->id);
                        route.handler(event);
                    } else {
                        EL_DEBUG("No WebSocket handler found for closed URI: {}", uri);
                    }
                } else {
                    EL_ERROR("WebSocket connection closed but URI not found in connection map");
                }
            }
            break;
        }
        case MG_EV_ERROR: {
            EL_ERROR("Connection error: {}", (const char *)ev_data);
            break;
        }
        default:
            break;
    }
}

void HttpServerImpl::SetSSLCert(const std::string &cert_file, const std::string &key_file)
{
    cert_file_ = cert_file;
    key_file_ = key_file;
}

void HttpServerImpl::AddBearerToken(const std::string &token)
{
    EL_DEBUG("Add bearer token: {}", token);
    bearer_tokens_.insert(token);
}

void HttpServerImpl::RemoveBearerToken(const std::string &token)
{
    EL_DEBUG("Remove bearer token: {}", token);
    bearer_tokens_.erase(token);
}

void HttpServerImpl::PrintBearerTokens() const
{
    EL_INFO("Current bearer tokens list:");
    if (bearer_tokens_.empty()) {
        EL_INFO("  No tokens available");
        return;
    }
    for (const auto &token : bearer_tokens_) {
        EL_INFO("  {}", token);
    }
}

void HttpServerImpl::AddAuthExemptUrl(const std::string &url_pattern)
{
    try {
        auth_exempt_urls_.emplace_back(url_pattern);
    } catch (const std::regex_error &e) {
        EL_ERROR("Invalid regex pattern for auth exempt URL: {}, error: {}", url_pattern, e.what());
    }
}

void HttpServerImpl::RemoveAuthExemptUrl(const std::string &url_pattern)
{
    // 移除所有匹配的正则表达式字符串
    auth_exempt_urls_.erase(std::remove_if(auth_exempt_urls_.begin(), auth_exempt_urls_.end(),
                                           [&url_pattern](const std::regex &r) {
                                               return r.flags() == std::regex::ECMAScript && r.mark_count() == 0 &&
                                                      std::regex_match(url_pattern, r);
                                           }),
                            auth_exempt_urls_.end());
}

bool HttpServerImpl::SendWebSocketBinaryMessage(void *connection, const std::vector<uint8_t> &data)
{
    if (connection == nullptr || data.empty()) {
        return false;
    }

    auto *c = static_cast<mg_connection *>(connection);
    if (c != nullptr && c->is_websocket) {
        mg_ws_send(c, data.data(), data.size(), WEBSOCKET_OP_BINARY);
        return true;
    }
    return false;
}

void HttpServerImpl::CloseWebSocketConnection(void *connection, int status_code, const std::string &reason)
{
    if (connection == nullptr) {
        return;
    }

    auto *c = static_cast<mg_connection *>(connection);
    if (c->is_websocket) {
        // 发送WebSocket关闭帧
        if (status_code > 0) {
            uint16_t code = static_cast<uint16_t>(status_code);
            std::vector<uint8_t> close_data;

            // 添加关闭状态码（网络字节序）
            close_data.push_back(static_cast<uint8_t>(code >> 8));
            close_data.push_back(static_cast<uint8_t>(code & 0xFF));

            // 添加关闭原因
            close_data.insert(close_data.end(), reason.begin(), reason.end());

            // 发送关闭帧
            mg_ws_send(c, close_data.data(), close_data.size(), WEBSOCKET_OP_CLOSE);
        }

        // 向所有WebSocket处理器发送关闭事件
        auto it = ws_connections_.find(static_cast<int64_t>(c->id));
        if (it != ws_connections_.end()) {
            const std::string &uri = it->second.uri;
            WebSocketRouteItem route;
            if (FindWebSocketRoute(uri, &route)) {
                auto event = std::make_shared<WebSocketEvent>();
                event->type = WebSocketEventType::Disconnect;
                event->connection = c;
                event->message = reason;
                route.handler(event);
            }
        }

        // 关闭连接
        c->is_closing = 1;
        EL_INFO("WebSocket connection closed with status code: {}, reason: {}", status_code, reason);
    }
}

bool HttpServerImpl::GetWebSocketConnectionInfo(void *connection, WebSocketConnectionInfo &info)
{
    if (connection == nullptr) {
        return false;
    }

    auto *c = static_cast<mg_connection *>(connection);
    if (!c->is_websocket) {
        return false;
    }

    std::lock_guard<std::mutex> lock(ws_mutex_);
    auto it = ws_connections_.find(static_cast<int64_t>(c->id));
    if (it != ws_connections_.end()) {
        info = it->second.info;
        return true;
    }

    return false;
}

std::vector<void *> HttpServerImpl::GetAllWebSocketConnections(const std::string &uri_pattern)
{
    std::vector<void *> connections;
    std::lock_guard<std::mutex> lock(ws_mutex_);

    if (uri_pattern.empty()) {
        // 返回所有WebSocket连接
        for (const auto &pair : ws_connections_) {
            connections.push_back(static_cast<void *>(pair.second.conn));
        }
    } else {
        // 尝试编译正则表达式
        std::regex uri_regex;
        try {
            uri_regex = std::regex(uri_pattern);
        } catch (const std::regex_error &e) {
            EL_ERROR("Invalid URI pattern for WebSocket connections: {}, error: {}", uri_pattern, e.what());
            return connections;
        }

        // 返回匹配的WebSocket连接
        for (const auto &pair : ws_connections_) {
            if (std::regex_match(pair.second.uri, uri_regex)) {
                connections.push_back(static_cast<void *>(pair.second.conn));
            }
        }
    }

    return connections;
}

int HttpServerImpl::BroadcastWebSocketMessage(const std::string &uri_pattern, const std::string &message)
{
    if (message.empty()) {
        return 0;
    }

    // 获取匹配的WebSocket连接
    std::vector<void *> connections = GetAllWebSocketConnections(uri_pattern);

    // 发送消息
    int sent_count = 0;
    for (void *conn : connections) {
        if (SendWebSocketTextMessage(conn, message)) {
            sent_count++;
        }
    }

    EL_INFO("WebSocket broadcast to {} connections, pattern: {}", sent_count, uri_pattern);
    return sent_count;
}

// 代理相关方法实现
void HttpServerImpl::InitializeCurl()
{
    if (!curl_initialized_) {
        curl_global_init(CURL_GLOBAL_DEFAULT);
        curl_initialized_ = true;
        EL_INFO("libcurl initialized for proxy functionality");
    }
}

void HttpServerImpl::CleanupCurl()
{
    if (curl_initialized_) {
        curl_global_cleanup();
        curl_initialized_ = false;
        EL_INFO("libcurl cleaned up");
    }
}

bool HttpServerImpl::RegisterProxyRule(const std::string &uri_pattern, 
                                       const std::vector<ProxyTarget> &targets,
                                       const ProxyOptions &options)
{
    std::lock_guard<std::mutex> lock(proxy_mutex_);
    
    // 检查是否已存在相同的规则
    for (const auto &rule : proxy_rules_) {
        if (rule.uri_pattern == uri_pattern) {
            EL_WARN("Proxy rule already exists for pattern: {}", uri_pattern);
            return false;
        }
    }
    
    // 创建新的代理规则
    ProxyRule rule;
    rule.uri_pattern = uri_pattern;
    rule.targets = targets;
    rule.options = options;
    
    try {
        rule.uri_regex = std::regex(uri_pattern);
    } catch (const std::regex_error &e) {
        EL_ERROR("Invalid proxy URI pattern: {}, error: {}", uri_pattern, e.what());
        return false;
    }
    
    proxy_rules_.push_back(rule);
    EL_INFO("Proxy rule registered: {} -> {} targets", uri_pattern, targets.size());
    return true;
}

bool HttpServerImpl::RemoveProxyRule(const std::string &uri_pattern)
{
    std::lock_guard<std::mutex> lock(proxy_mutex_);
    
    auto it = std::find_if(proxy_rules_.begin(), proxy_rules_.end(),
                          [&uri_pattern](const ProxyRule &rule) {
                              return rule.uri_pattern == uri_pattern;
                          });
    
    if (it != proxy_rules_.end()) {
        proxy_rules_.erase(it);
        EL_INFO("Proxy rule removed: {}", uri_pattern);
        return true;
    }
    
    EL_WARN("Proxy rule not found: {}", uri_pattern);
    return false;
}

void HttpServerImpl::SetProxyGlobalTimeout(int timeout_ms)
{
    proxy_global_timeout_ = timeout_ms;
    EL_INFO("Proxy global timeout set to: {}ms", timeout_ms);
}

void HttpServerImpl::SetProxyGlobalRetry(int retry_count)
{
    proxy_global_retry_ = retry_count;
    EL_INFO("Proxy global retry count set to: {}", retry_count);
}

void HttpServerImpl::EnableProxyLogging(bool enabled)
{
    proxy_logging_enabled_ = enabled;
    EL_INFO("Proxy logging {}", enabled ? "enabled" : "disabled");
}

// libcurl回调函数实现
size_t HttpServerImpl::WriteCallback(void *contents, size_t size, size_t nmemb, std::string *data)
{
    size_t realsize = size * nmemb;
    data->append(static_cast<char*>(contents), realsize);
    return realsize;
}

size_t HttpServerImpl::HeaderCallback(void *contents, size_t size, size_t nmemb, std::map<std::string, std::string> *headers)
{
    size_t realsize = size * nmemb;
    std::string header_line(static_cast<char*>(contents), realsize);
    
    // 查找冒号分隔符
    size_t pos = header_line.find(':');
    if (pos != std::string::npos) {
        std::string key = header_line.substr(0, pos);
        std::string value = header_line.substr(pos + 1);
        
        // 去除前后空格
        key.erase(0, key.find_first_not_of(" \t"));
        key.erase(key.find_last_not_of(" \t\r\n") + 1);
        value.erase(0, value.find_first_not_of(" \t"));
        value.erase(value.find_last_not_of(" \t\r\n") + 1);
        
        if (!key.empty() && !value.empty()) {
            (*headers)[key] = value;
        }
    }
    
    return realsize;
}

// 代理规则匹配逻辑
bool HttpServerImpl::MatchProxyRule(const std::string &uri, ProxyRule &matched_rule)
{
    std::lock_guard<std::mutex> lock(proxy_mutex_);
    
    for (auto &rule : proxy_rules_) {
        if (std::regex_match(uri, rule.uri_regex)) {
            matched_rule = rule;
            return true;
        }
    }
    
    return false;
}

// 目标选择逻辑 (简单轮询)
ProxyTarget HttpServerImpl::SelectTarget(const std::vector<ProxyTarget> &targets, ProxyRule &rule)
{
    // 过滤出启用的目标
    std::vector<ProxyTarget> enabled_targets;
    for (const auto &target : targets) {
        if (target.enabled) {
            enabled_targets.push_back(target);
        }
    }
    
    if (enabled_targets.empty()) {
        throw std::runtime_error("No enabled proxy targets available");
    }
    
    // 简单轮询选择
    size_t index = rule.current_target_index % enabled_targets.size();
    rule.current_target_index++;
    
    return enabled_targets[index];
}

// 构建代理URL
std::string HttpServerImpl::BuildProxyUrl(const ProxyTarget &target, const std::string &uri, const ProxyRule &rule)
{
    std::string result_uri = uri;
    
    // 处理前缀移除
    if (!rule.options.strip_prefix.empty()) {
        if (result_uri.find(rule.options.strip_prefix) == 0) {
            result_uri = result_uri.substr(rule.options.strip_prefix.length());
        }
    }
    
    // 处理前缀添加
    if (!rule.options.add_prefix.empty()) {
        result_uri = rule.options.add_prefix + result_uri;
    }
    
    // 确保URI以/开头
    if (!result_uri.empty() && result_uri[0] != '/') {
        result_uri = "/" + result_uri;
    }
    
    // 构建完整URL
    std::string protocol = target.use_https ? "https" : "http";
    return protocol + "://" + target.host + ":" + std::to_string(target.port) + result_uri;
}

// 代理请求处理
bool HttpServerImpl::HandleProxyRequest(const HttpRequest &request, HttpResponse &response)
{
    ProxyRule matched_rule;
    if (!MatchProxyRule(request.uri, matched_rule)) {
        return false;  // 不匹配代理规则，走正常处理
    }
    
    if (proxy_logging_enabled_) {
        EL_INFO("Proxy request matched: {} -> pattern: {}", request.uri, matched_rule.uri_pattern);
    }
    
    return ForwardRequest(request, matched_rule, response);
}

// 转发请求到目标服务器
bool HttpServerImpl::ForwardRequest(const HttpRequest &request, const ProxyRule &rule, HttpResponse &response)
{
    try {
        // 选择目标服务器
        ProxyTarget target = SelectTarget(rule.targets, const_cast<ProxyRule&>(rule));
        
        // 构建代理URL
        std::string proxy_url = BuildProxyUrl(target, request.uri, rule);
        
        if (proxy_logging_enabled_) {
            EL_INFO("Forwarding {} {} to {}", request.method, request.uri, proxy_url);
        }
        
        // 使用libcurl发送请求
        CURL* curl = curl_easy_init();
        if (!curl) {
            EL_ERROR("Failed to initialize curl for proxy request");
            response.status_code = 502;
            response.body = "Bad Gateway - curl init failed";
            return false;
        }
        
        std::string response_data;
        std::map<std::string, std::string> response_headers;
        
        // 设置基本curl选项
        curl_easy_setopt(curl, CURLOPT_URL, proxy_url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_data);
        curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, HeaderCallback);
        curl_easy_setopt(curl, CURLOPT_HEADERDATA, &response_headers);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, rule.options.timeout_ms > 0 ? rule.options.timeout_ms : proxy_global_timeout_);
        
        // 设置SSL选项
        if (target.use_https) {
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
            curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        }
        
        // 设置请求方法和数据
        if (request.method == "POST") {
            curl_easy_setopt(curl, CURLOPT_POST, 1L);
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.body.c_str());
            curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request.body.length());
        } else if (request.method == "PUT") {
            curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.body.c_str());
            curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request.body.length());
        } else if (request.method == "DELETE") {
            curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
        } else if (request.method == "HEAD") {
            curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
        }
        
        // 设置请求头
        struct curl_slist* headers = nullptr;
        
        // 复制原始请求头
        for (const auto& header : request.headers) {
            if (header.first == "Host" && !rule.options.preserve_host) {
                // 如果不保留原始Host头，则设置为目标服务器的Host
                std::string host_header = "Host: " + target.host + ":" + std::to_string(target.port);
                headers = curl_slist_append(headers, host_header.c_str());
            } else if (header.first != "Content-Length") {  // 让curl自动处理Content-Length
                std::string header_line = header.first + ": " + header.second;
                headers = curl_slist_append(headers, header_line.c_str());
            }
        }
        
        // 添加配置中的额外请求头
        for (const auto& header : rule.options.headers) {
            std::string header_line = header.first + ": " + header.second;
            headers = curl_slist_append(headers, header_line.c_str());
        }
        
        if (headers) {
            curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        }
        
        // 执行请求
        CURLcode res = curl_easy_perform(curl);
        
        // 获取响应状态码
        long response_code;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
        
        // 清理
        if (headers) {
            curl_slist_free_all(headers);
        }
        curl_easy_cleanup(curl);
        
        if (res != CURLE_OK) {
            EL_ERROR("Proxy request failed: {} (code: {})", curl_easy_strerror(res), res);
            response.status_code = 502;
            response.body = "Bad Gateway - " + std::string(curl_easy_strerror(res));
            return false;
        }
        
        // 构建响应
        response.status_code = static_cast<int>(response_code);
        response.body = response_data;
        
        // 设置响应头(过滤掉不需要的头)
        for (const auto& header : response_headers) {
            if (header.first != "Transfer-Encoding" && 
                header.first != "Connection" && 
                header.first != "Content-Encoding") {
                // 某些头可能需要过滤，让服务器自己处理
                if (header.first == "Content-Type") {
                    response.content_type = header.second;
                }
            }
        }
        
        if (proxy_logging_enabled_) {
            EL_INFO("Proxy response: {} bytes, status: {}", response.body.length(), response.status_code);
        }
        
        return true;
        
    } catch (const std::exception &e) {
        EL_ERROR("Proxy request exception: {}", e.what());
        response.status_code = 502;
        response.body = "Bad Gateway - " + std::string(e.what());
        return false;
    }
}

} // namespace WebServer
} // namespace El